package com.magupe.develop.data.linked;

import javax.xml.soap.Node;

public class Node4 {

    public int value;    // 数据
    public Node4 next;   // 下一节点

    public Node4(){}

    public Node4(int value){
        this.value = value;
    }

    public Node4 setNext(Node4 next) {
        this.next = next;
        return this;
    }

    public boolean hasNext(){
        return this.next != null ? true : false;
    }

    // 尾部插入
    public void addToTail(Node4 node){
        Node4 temp = this;
        while(temp.hasNext()){
            temp = temp.next;
        }
        temp.next = node;
    }

    // 头部插入
    public void addToHead(Node4 head, Node4 node){
        node.next = head.next;
        head.next = node;
    }

    // 从某个节点插入
    public Node4 addToNext(Node4 node){
        node.next = this.next;
        this.next = node;
        return node;
    }

    // 链表逆转
    public static Node4 reverse(Node4 first){
        Node4 cur = first;      // 前驱节点
        Node4 pre = null;       // 当前节点
        while(cur.hasNext()){
            Node4 after = cur.next;         // 标记出来下一个操作的节点
            cur.setNext(pre);               // 当前节点指向前驱节点
            pre = cur;                      // 现有当前节点改为前驱节点
            cur = after;                    // 现有下一个节点 改为当前需要操作的节点
        }
        cur.setNext(pre);                   // 到最末尾的时候直接
        return cur;
    }

    @Override
    public String toString() {
        String val = Integer.toString(this.value);
        if(this.next != null){
            val = val.concat(" hasNext ");
            val = val.concat(this.next.toString());
        }
        return val;
    }

    public static void main(String[] args) {
        // 第一个节点
        Node4 first = new Node4(1);

        // 第二个节点
        Node4 second = new Node4(2);

        // 第三个节点
        Node4 third = new Node4(3);

        // 第四个节点
        Node4 fourth = new Node4(4);

        // 链接
        first.addToNext(second).addToNext(third).addToNext(fourth);

        //System.out.println(first.getNext().getNext().getNext().getValue());
        System.out.println(first);

        Node4 node4 = reverse(first);
        System.out.println(node4);
    }
}
